package com.sure0000.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutionException;
import java.lang.InterruptedException;

public class ThreadPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("1");
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                }
            }
        });

        int systemCores = Runtime.getRuntime().availableProcessors();   // 系统 cpu 核数
        int corePoolSize = systemCores;
        int maxPoolSize = 10 * corePoolSize;
        int keepAliveTime = 100;
        int queueCapacity = 200;

        ExecutorService executorService = 
        new ThreadPoolExecutor(
            corePoolSize, 
            maxPoolSize, 
            keepAliveTime, 
            TimeUnit.SECONDS, 
            new ArrayBlockingQueue<>(queueCapacity),
            new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread rThread = new Thread(r);
                    rThread.setName("xyc_" + rThread.getName());
                    return rThread;
                }
            },
            new ThreadPoolExecutor.AbortPolicy()    // 线程阻塞策略
        );

        // 执行 runnable 线程
        executorService.execute(thread1);

        // 执行 callable 线程
        Future future = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    Thread.sleep(5000L);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                return "hello 5";
            }
        });

        while(true){
            if(future.isDone()) {
                System.out.println(future.get());
                break;
            }
            System.out.println("XXXXXXXXXXX");
            try {
                Thread.sleep(1000L);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        // 关闭线程池
        executorService.shutdown();
    }
}